//
//  comingthingViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/25.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "chuguoViewController.h"
#import "huiyiViewController.h"
#import "diannaoViewController.h"
#import "bangongViewController.h"
#import "chucaiViewController.h"
#import "comingthingViewController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "detailViewController.h"
#import "OADetailViewController.h"
#import "PickerChoiceView.h"
#import "NewworkViewController.h"
#define  ktansactiontodoPage @"tansactiontodoPage" //待办 分页列表

@interface comingthingViewController ()<TFPickerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSInteger selectIndex;
        NSArray *titles;

}
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property (nonatomic,strong)NSMutableArray *mutArray;


@end

@implementation comingthingViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
    [self.tableView addHeaderWithCallback:^{
        self.currentPage = 1;

        [self loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [self loadMore];
        }else{
        
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
    
        }
       
    }];
    [self setRightItem];
     NSArray *arr = @[@{@"title1":@"请点击此处选择星期",@"title2":@"星期一"}];
    for (NSDictionary *dict in arr) {
        
        [self.mutArray addObject:dict];
    }

}

-(void)setRightItem{
            UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"拟稿" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;
   
    
}
- (void)searchAction{
//PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
//       picker.delegate = self;
//
//        
//        picker.selectLb.text = @"拟办选择";
//        picker.customArr = @[@"请假申请",@"出差审批",@"专网/官网信息发布审批",@"会议室使用",@"会议备案审批",@"接待管理",@"用车审批",];
//  
//
//    [self.view addSubview:picker];
    titles = @[@"请假申请",@"出差审批",@"出国审批",@"会议备案审批",@"办公用品申请",@"电脑耗材"];
  
    [SelectAlert showWithTitle:@"选择拟稿类型" titles:titles selectIndex:^(NSInteger selectIndex) {
    } selectValue:^(NSString *selectValue) {
    NSLog(@"%@",selectValue);
if ([selectValue isEqualToString:@"请假申请"]) {
//
NewworkViewController *vc = [[NewworkViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}else if([selectValue isEqualToString:@"出差审批"]){
 chucaiViewController*vc = [[chucaiViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}else if([selectValue isEqualToString:@"出国审批"]){
chuguoViewController*vc = [[chuguoViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}else if([selectValue isEqualToString:@"会议备案审批"]){
huiyiViewController*vc = [[huiyiViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];



}else if([selectValue isEqualToString:@"办公用品申请"]){
bangongViewController*vc = [[bangongViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}else if([selectValue isEqualToString:@"电脑耗材"]){
diannaoViewController*vc = [[diannaoViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];

}else{
//用车审批

}


} showCloseButton:YES];




}

#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
      _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    //KGetOAOfficeMethod
    //ktansactiontodoPage
    [HttpTools postWithURL:kexmoreworkings
     arrays:array method:ktansactiontodoPage success:^(id JSON) {
     // NSLog(@"-------%@",JSON);

        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
       
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有待办事项哦"];
        }
    } failure:^(NSError *error) {
     [self.tableView headerEndRefreshing];
        
    }];
 
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:kexmoreworkings arrays:array method:ktansactiontodoPage success:^(id JSON) {
           [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * signElement = [[data elementsForName:@"isSign"] objectAtIndex:0];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.isSign = [signElement stringValue];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
     self.title = [NSString stringWithFormat:@"待办事项(%lu)",(unsigned long)self.totalCounts];
   
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UnDoneModel * model = self.dataArray[indexPath.row];
    CGFloat  titleFloat  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    NSString * desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    CGFloat desFloat = [OAToolBox sizebyText:desstring font:14 minsWidth:80];
    return  titleFloat + desFloat + 20;
//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
    UnDoneModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UnDoneModel * model = self.dataArray[indexPath.row];
OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[self.storyboard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
 //detailVC.isAlreadDoneWork = YES;
detailVC.fileId = model.fileId;
 if ([model.isSign isEqualToString:@"1"]) {
            detailVC.isUnDoWork = NO;
        }else{
            detailVC.isUnDoWork = YES;
        }
        detailVC.hidesBottomBarWhenPushed = YES;

[self.navigationController pushViewController:detailVC animated:YES];    


}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
